<template>
  <div class="ImageDetection" >
    <div class="select">
      <label for="class" class="classLabel">选择班级：</label>
      <select id="class" v-model="selectedClass">
        <option disabled selected>选择班级</option>
        <option v-for="Class in Classes" :key="Class" :value="Class">
          {{ Class }}
        </option>
      </select>
      <label for="course" class="courseLabel">选择课程：</label>
      <select id="course" v-model="selectedCourse">
        <option disabled selected>选择课程</option>
        <option v-for="Course in Courses" :key="Course" :value="Course">
          {{ Course }}
        </option>
      </select>
      <el-button
      class="start"
    type="primary"
    @click="Detection">
    开始检测
  </el-button>
      <label class="tip1">{{ tip1 }}</label>
    </div>
    <input
      type="file"
      ref="fileInput"
      style="display: none"
      @change="handleImageChange"
    />
    <div>
      <div class="picture" @click="triggerFileInput">
        <h6 class="tip" v-show="!SelectedImage">选择图片</h6>
        <img
          v-if="SelectedImage"
          :src="SelectedImage"
          alt="SelectedImage"
          style="width: 100%; height: 100%"
        />
      </div>
      <div class="pieOfDate">
        <Pie :reach="reachNumber" :absence="absentNumber"></Pie>
      </div>
      <div class="pictureOfData">
        <Histogram :number="numberOfActions"></Histogram>
      </div>
      <div class="reachInformation">
        <label class="label">应到：{{ this.absentNumber + this.reachNumber }}人</label>
        <label class="label">实到：{{ this.reachNumber }}人</label>
        <label class="label">缺勤：{{ this.absentNumber }}人</label>
        <label class="label">到课率：{{ this.attendanceRate }}</label>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { serverAddress } from "../js/config";
import { CircleSpinner } from 'vue-spinners';
import Histogram from "./Histogram.vue";
import Pie from "./Pie.vue";
export default {
  name: "ImageDetection",
  components: {
    serverAddress,
    Histogram,
    Pie,
    CircleSpinner,
  },
  data() {
    return {
      Loading: false,
      uploadProgress: 0,
      selectedClass: null,
      selectedCourse: null,
      Classes: [1, 2, 3, 4, 5],
      Courses: [
        "高等数学",
        "Java程序设计",
        "大学英语",
        "概率论",
        "计算机组成原理",
        "数据库原理",
      ],
      SelectedImage: null,
      ToImage: null,
      tip1: "",
      numberOfActions: [0, 0, 0, 0, 0],
      reachNumber: 0,
      absentNumber: 0,
      attendanceRate: 0,
    };
  },
  methods: {
    triggerFileInput() {
      // 通过引用（ref）调用文件输入框的点击事件
      this.$refs.fileInput.click();
    },
    handleImageChange(event) {
      const file = event.target.files[0];
      this.ToImage = file;
      // 获取选择的文件
      if (file) {
        // 将图片转为 Base64 格式
        const reader = new FileReader();
        reader.onload = () => {
          // 将 Base64 数据存储在 selectedImage 中
          this.SelectedImage = reader.result;
        };
        reader.readAsDataURL(file);
        console.log(this.SelectedImage);
      }
    },
    Detection() {
      if (
        this.selectedClass !== null &&
        this.selectedCourse !== null &&
        this.ToImage !== null
      ) {
        const loading = this.$loading({
          target:document.querySelector('.picture'),
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(100, 100, 100, 0.3)'
        });
        var api=`${serverAddress}/PictureUpload/teacher`;
        let formData = new FormData();
        formData.append("class_idd", this.selectedClass);
        formData.append("course_name", this.selectedCourse);
        if(sessionStorage.getItem('Identity')==='教师'){
          formData.append(
          "teacher_id",
          sessionStorage.getItem('Id'),
        );
        }
        if(sessionStorage.getItem('Identity')==='管理员'){
          api=`${serverAddress}/PictureUpload/root`;
          formData.append(
          "root_id",
          sessionStorage.getItem('Id'),
        );
        }
        formData.append("pictureUpload", this.ToImage);

        console.log(formData);
        axios({
          /* url: `${serverAddress}/PictureUpload/teacher`, */
          url: "https://mock.apifox.com/m2/3662090-0-default/131249140",
          method: "POST",
          data: formData, // 使用 FormData 对象作为请求的数据
          headers: {
            "Content-Type": "multipart/form-data", // 设置请求头 Content-Type
          },
          onUploadProgress: (progressEvent) => {
        const progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
        this.uploadProgress = progress;
      },
        }).then((response) => {
          loading.close();
          if (response.data.code === 1) {
            console.log(response.data);
            this.SelectedImage = response.data.data.changePicture;
            this.$set(this, "numberOfActions", [
              response.data.data.pictureReadCount,
              response.data.data.pictureHandsCount,
              response.data.data.pictureWriteCount,
              response.data.data.absentNumber,
              response.data.data.pictureNumber -
                response.data.data.pictureReadCount -
                response.data.data.pictureHandsCount -
                response.data.data.pictureWriteCount,
            ]);
            console.log(this.numberOfActions);
            this.reachNumber = response.data.data.pictureNumber;
            this.absentNumber = response.data.data.absentNumber;
            this.attendanceRate = response.data.data.pictureRatio;
          } else {
            console.log(response.data);
            this.tip1 = response.data.msg;
            setTimeout(() => {
              this.tip1 = "";
            }, 5000);
          }
        });
      } else {
        this.tip1 = "请确认班级，课程，图片均不为空";
        setTimeout(() => {
          this.tip1 = "";
        }, 5000);
      }
    },
  },
};
</script>

<style scoped>
.label {
  font-size: 18px;
  font-weight: bold;
  padding: 8px;
  color: #2c3e50;
}

.reachInformation {
  width: 175px;
  height: 125px;
  position: absolute;
  top: 110px;
  left: 960px;
  display: flex;
  flex-direction: column;
  border-radius: 10px;
  padding: 10px;
  text-align: center;
}

.reachInformation label {
  margin-bottom: 10px;
}

.reachInformation .label {
  background-color: #76a2ed;
  color: #fff;
  border-radius: 5px;
}

.reachInformation .label:first-child {
  margin-top: 10px;
}


.pieOfDate {
  position: absolute;
  left: 730px;
  top: 105px;
}
.tip1 {
  color: rgb(217, 83, 83);
  font-size: 15px;
  width: 380px;
  height: 20px;
  position: absolute;
  top: 13%;
  left: 65%;
  z-index: 50;
}
.start {
  text-align: center;
  padding: 9px;
  border: 2px solid #a1bce1;
  border-radius: 23px;
  font-weight: 700;
  font-size: 17px;
  width: 120px;
  background-image: linear-gradient(to right, #a6c1ee, #fbc2eb);
  color: #fff;
  position: absolute;
  top: 40px;
  left: 830px;
}
.tip {
  color: #a1bce1;
  font-size: 20px;
  font-weight: 300;
  font-family: "黑体";
  position: absolute;
  top: 35%;
  left: 44%;
}

.picture {
  background-color: rgb(255, 255, 255);
  border: 1.5px dashed #a1bce1;
  width: 650px;
  height: 450px;
  position: absolute;
  top: 130px;
  left: 40px;
}
.pictureOfData {
  width: 430px;
  height: 270px;
  position: absolute;
  top: 340px;
  left: 720px;
}
#class,
#course {
  width: 100px;
  height: 30px;
  border: 2px solid #a1bce1;
  border-radius: 10px;
  position: absolute;
  top: 8%;
}
.classLabel,
.courseLabel {
  font-size: 17px;
  font-family: "黑体";
  position: absolute;
  top: 9%;
}
.classLabel {
  left: 11.5%;
}
.courseLabel {
  left: 31.5%;
}
#class {
  left: 18%;
}
#course {
  left: 38%;
}
</style>